﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CoyoEden.Models;
using CoyoEden.Web.Data;
using Vivasky.Core.Infrastructure;

namespace CoyoEden.Web.Controller
{
	public class CommunityController:ControllerBase
	{
		/// <summary>
		/// select a single record
		/// </summary>
		public static Community Single(Dictionary<string, string> Params, out FeedbackData msg)
		{
			msg = new FeedbackData();
			var user = Params["user"];
			var id = Convert.ToInt32(Params["id"]);
			Community tempObj = null;
			try
			{
				if (id < 0)
				{
					tempObj = new Community();
				}
				else
				{
					tempObj = Community.GetCommunity(id);
					if (tempObj == null)
					{
						msg.Body = string.Format("<h3>无法获取此社区(编号:{0})的信息.</h3>", id);
					}
				}
			}
			catch (Exception ex)
			{
				ResolveException(ex, out msg);
			}
			return tempObj;
		}
		public static void Update(List<NameValuePair<string, string>> Params, out FeedbackData msg)
		{
			msg = new FeedbackData();
			try
			{
				//need validate user?
				var user = Params.Find(item => item.name == "user");

				var id = Convert.ToInt32(Params.Find(item => item.name == "CommunityId").value);
				Community tempObj = null;
				if (id <= 0)
				{
					tempObj = new Community();
				}
				else
				{
					tempObj = Community.Communities.Find(c => c.Id == id);
				}
				tempObj.Name = Params.Find(item => item.name == "CommunityName").value;
				tempObj.Description = Params.Find(item => item.name == "CommunityDesc").value;
				tempObj.Slug = Params.Find(item => item.name == "CommunitySlug").value;
				tempObj.Icon = Params.Find(item => item.name == "CommunityIcon").value;
				tempObj.Icon = Utils.ConvertToRelative(tempObj.Icon,true);
				if (string.IsNullOrEmpty(tempObj.Icon))
				{
					tempObj.Icon = Community.NoIcon;
				}
				tempObj.Parent = Convert.ToInt32(Params.Find(item => item.name == "CommunityParent").value);
				tempObj.Save(out msg);
			}
			catch (Exception ex)
			{
				ResolveException(ex, out msg);
			}
		}
		public static void Delete(Dictionary<string, string> Params, out FeedbackData msg)
		{
			msg = new FeedbackData();
			try
			{
				var keys = Params["keys"];
				var user = Params["user"];
				List<string> communityIDs = keys.Split('|').ToList();
				//delete categories
				communityIDs.ForEach(c =>
				{
					Community cat = Community.GetCommunity(Convert.ToInt32(c));
					Topic.Topics.ForEach(topic =>
					{
						if (topic.Communities.Contains(cat))
						{
							topic.Communities.Remove(cat);
						}
					});
					cat.Delete();
					cat.Save();
				});
			}
			catch (Exception ex)
			{
				ResolveException(ex, out msg);
			}
		}
	}
}
